package com.atguigu.tingshu.order.task;

import com.atguigu.tingshu.order.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Slf4j
@Component
public class RedisDelayQueueHandler {
    @Autowired
    private RedissonClient redissonClient ;

    @Autowired
    private OrderInfoService orderInfoService;

    //定时任务 也是获取延迟任务队列
    @Scheduled(cron = "0/1 * * * * ?")
    public void orderInfoDelayQueue() {         // 使用分布式锁的目的：在集群环境下防止任务的重复执行

        // 获取锁对象
        RLock lock = redissonClient.getLock("order:info:delay:queue:lock");
        //延迟队列 获取延迟任务
        boolean tryLock = lock.tryLock();
        if(tryLock) {

            try {

                // log.info("RedisDelayQueueHandler...orderInfoDelayQueue...方法执行了...");
                RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque("order:info:delay:queue");
                String orderNo = blockingDeque.poll();         //获取到延迟任务
                if(!StringUtils.isEmpty(orderNo)) {
                    orderInfoService.orderCancel(orderNo) ;
                    log.info("执行取消订单的操作成功了....orderNo:{}", orderNo);
                }

            }catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e) ;
            } finally {
                lock.unlock();   // 释放锁对象
            }

        }

    }
}
